#include "halloffamedisplay.h"

HallOfFameDisplay::HallOfFameDisplay(QWidget *parent, QString url) :
    QTableWidget(parent),
    list_url (url)
{
    // Setup UI
    setMinimumWidth(400);
    setMinimumHeight(500);
    horizontalHeader()->setStretchLastSection(true);
    setColumnCount(3);
    QStringList labels;
    labels << "Name" << "Points" << "Time";
    setHorizontalHeaderLabels(labels);

    // Read hall of fame
    readFile();

    // Update UI
    setSortingEnabled(true);
    sortByColumn(1);
    setColumnWidth(0, 200);
}

void HallOfFameDisplay::readFile()
{
    // Open hall of fame file (read only)
    QFile * f = new QFile(list_url);
    if(f->open(QIODevice::ReadOnly | QIODevice::Text)) {
        // Setup text stream
        QTextStream in(f);
        // Current row container
        int i = 0;
        do {
            // Read line, separator |, check validity
            QStringList str_list = in.readLine().split("|");
            if( str_list.length() != 3 ) continue;

            insertRow(i);

            // Name column
            QTableWidgetItem * item = new QTableWidgetItem(str_list.at(0));
            item->setFlags(Qt::ItemIsEnabled);
            setItem(i,0,item);

            // Points column
            item = new QTableWidgetItem;
            item->setFlags(Qt::ItemIsEnabled);
            item->setData(Qt::EditRole, str_list.at(1).toInt());
            setItem(i,1,item);

            // Time column (human readable)
            item = new QTableWidgetItem;
            QTime time = QTime(0,0,0,0);
            item->setFlags(Qt::ItemIsEnabled);
            time = time.addMSecs(str_list.at(2).toInt());
            item->setData(Qt::EditRole, time.toString());
            setItem(i,2,item);

            // New row
            i++;
        } while( !in.atEnd() );
        f->close();
    }
}
